using MediatR;
using Medical.Domain;
using Medical.Infrastructrue.Interfaces;
using Medical.ReadApi.Dto;
using Medical.WriteApi.Appcontext.Command;
using Medical.WriteApi.Dto;

namespace Medical.WriteApi.Appcontext.CommandHandler
{
	public class UpdateRoleCommandHandler : IRequestHandler<UpdateRoleCommand, RoleDto>
	{
		private readonly IBaseRepository<Role> _repository;

		public UpdateRoleCommandHandler(IBaseRepository<Role> repository)
		{
			_repository = repository;
		}

		public async Task<RoleDto> Handle(UpdateRoleCommand request, CancellationToken cancellationToken)
		{
			var role = await _repository.GetModel(x => x.RoleId == request.RoleId);
			if (role == null) throw new Exception("角色不存在");
			if (!string.IsNullOrEmpty(request.Name)) role.Name = request.Name;
			if (request.Description != null) role.Description = request.Description;
			if (request.IsActive.HasValue) role.IsActive = request.IsActive.Value;
			role.UpdatedAt = DateTime.Now;
			await _repository.UpdateAsync(role);
			return new RoleDto { RoleId = role.RoleId, Name = role.Name, Description = role.Description, IsActive = role.IsActive, CreatedAt = role.CreatedAt, UpdatedAt = role.UpdatedAt };
		}
	}
}
